package com.borqsprocessmanager.sample;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;

import com.borqsprocessmanager.App;
import com.borqsprocessmanager.ConfigParams;
import com.borqsprocessmanager.Constant;
import com.borqsprocessmanager.info.ProcessStatsInfo;
import com.borqsprocessmanager.util.Log;

public class SignalChangedModule extends PhoneStateListener implements
        ASampleMoudle {
    private final String TAG = "SignalChangedModule";

    // private final long BASE_LINE = 10;

    private Context mContext;
    // private int strength;
    private long startTime;
    private long moderateTime;

    public SignalChangedModule(Context context) {
        mContext = context;
        startListenSignalStrengtheChanged();
    }

    public void startListenSignalStrengtheChanged() {
        TelephonyManager Tel = (TelephonyManager) App.mContext
                .getSystemService(Context.TELEPHONY_SERVICE);
        Tel.listen(this, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }

    @Override
    public void onSignalStrengthsChanged(SignalStrength signalStrength) {
        super.onSignalStrengthsChanged(signalStrength);
        int strength = signalStrength.getGsmSignalStrength();
        if (strength < 6) {
            if (startTime == 0) {
                startTime = System.currentTimeMillis();
            } else {
                long curTime = System.currentTimeMillis();
                moderateTime += curTime - startTime;
                startTime = curTime;
            }
        } else {
            startTime = 0;
        }
    }

    @Override
    public ArrayList<ProcessStatsInfo> sample(int sample_id, int type,
            HashMap<String, ProcessStatsInfo> whiteMap) {
        ArrayList<ProcessStatsInfo> list = null;
        switch (type) {
        case TYPE_GETDATA_AND_CONTINUE:
            Log.v(TAG, "moderateTime===" + moderateTime);
            list = createResInfo(sample_id);
            break;
        }
        init();
        return list;
    }

    private ArrayList<ProcessStatsInfo> createResInfo(int samlpeId) {
        if (moderateTime > ConfigParams.SIGNAL_BASELINE) {
            ArrayList<ProcessStatsInfo> list = new ArrayList<ProcessStatsInfo>();
            ProcessStatsInfo info = new ProcessStatsInfo();
            info.setSampleId(samlpeId);
            info.setType(Constant.TYPE_SIGNAL_LOW);
            list.add(info);
            Log.v(TAG, "createResInfo_list.size===" + list.size());
            return list;
        }
        return null;
    }

    private void init() {
        moderateTime = 0;
        if (startTime != 0) {
            startTime = System.currentTimeMillis();
        }
    }

    @Override
    public ArrayList<ProcessStatsInfo> getSampleRes() {
        // TODO Auto-generated method stub
        return null;
    }
}
